package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.wms.entity.WmsPurchaseOrderDetail;
import org.jeecg.modules.wms.mapper.WmsPurchaseOrderDetailMapper;
import org.jeecg.modules.wms.service.IWmsPurchaseOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description: 采购单明细Service实现类
 * @Author: jeecg-boot
 * @Date: 2023-07-17
 * @Version: V1.0
 */
@Service
public class WmsPurchaseOrderDetailServiceImpl extends ServiceImpl<WmsPurchaseOrderDetailMapper, WmsPurchaseOrderDetail> implements IWmsPurchaseOrderDetailService {

    @Autowired
    private WmsPurchaseOrderDetailMapper wmsPurchaseOrderDetailMapper;

    @Override
    public List<WmsPurchaseOrderDetail> selectByPurchaseOrderId(String purchaseOrderId) {
        return wmsPurchaseOrderDetailMapper.selectByPurchaseOrderId(purchaseOrderId);
    }

    @Override
    @Transactional
    public boolean deleteByPurchaseOrderId(String purchaseOrderId) {
        int count = wmsPurchaseOrderDetailMapper.deleteByPurchaseOrderId(purchaseOrderId);
        return count > 0;
    }

    @Override
    @Transactional
    public boolean updateReceivedQuantity(String id, BigDecimal receivedQuantity) {
        int count = wmsPurchaseOrderDetailMapper.updateReceivedQuantity(id, receivedQuantity);
        return count > 0;
    }

    @Override
    @Transactional
    public boolean saveBatch(String purchaseOrderId, List<WmsPurchaseOrderDetail> detailList) {
        // 先删除原有明细
        wmsPurchaseOrderDetailMapper.deleteByPurchaseOrderId(purchaseOrderId);
        
        // 添加新的明细
        if (detailList != null && !detailList.isEmpty()) {
            for (WmsPurchaseOrderDetail detail : detailList) {
                detail.setPurchaseOrderId(purchaseOrderId);
                if (detail.getReceivedQuantity() == null) {
                    detail.setReceivedQuantity(BigDecimal.ZERO);
                }
            }
            return super.saveBatch(detailList);
        }
        
        return true;
    }

    @Override
    public List<WmsPurchaseOrderDetail> selectLatestByMaterialCode(String materialCode, int limit) {
        return wmsPurchaseOrderDetailMapper.selectLatestByMaterialCode(materialCode, limit);
    }
    
    @Override
    public List<WmsPurchaseOrderDetail> queryDetailList(String purchaseOrderId) {
        // 直接调用已有的方法
        return this.selectByPurchaseOrderId(purchaseOrderId);
    }
} 